#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
一键启动全面MES系统
"""
import subprocess
import os
import time
import sys

def start_mes_services():
    """启动所有MES服务"""
    # 切换到项目目录
    os.chdir('/home/ubuntu/zlymes/mesmaster')
    
    print("=== 全面MES系统启动 ===")
    print("正在启动所有服务...")
    
    # 停止现有服务
    print("停止现有服务...")
    subprocess.run(['pkill', '-f', 'python manage.py runserver'], 
                   capture_output=True, text=True)
    
    time.sleep(2)
    
    # 启动三个服务
    services = [
        {
            'name': '基础MES服务',
            'port': '8004',
            'log': '/tmp/final_mes_8004.log'
        },
        {
            'name': '完整MES服务', 
            'port': '8005',
            'log': '/tmp/final_mes_8005.log'
        },
        {
            'name': 'Django管理服务',
            'port': '8006', 
            'log': '/tmp/final_mes_8006.log'
        }
    ]
    
    processes = []
    for service in services:
        print(f"启动 {service['name']} (端口 {service['port']})...")
        
        # 启动服务
        cmd = [
            'python', 'manage.py', 'runserver', 
            f"0.0.0.0:{service['port']}", 
            '--settings=settings_final_mes'
        ]
        
        with open(service['log'], 'w') as log_file:
            process = subprocess.Popen(
                cmd,
                stdout=log_file,
                stderr=subprocess.STDOUT,
                cwd='/home/ubuntu/zlymes/mesmaster'
            )
            processes.append((process, service))
        
        time.sleep(2)
    
    # 等待服务启动
    print("等待服务启动...")
    time.sleep(8)
    
    # 检查服务状态
    print("\n=== 服务状态检查 ===")
    success_count = 0
    for process, service in processes:
        if process.poll() is None:  # 进程仍在运行
            print(f"✅ {service['name']} - 正常运行 (PID: {process.pid})")
            success_count += 1
        else:
            print(f"❌ {service['name']} - 启动失败")
            # 显示错误日志
            try:
                with open(service['log'], 'r') as f:
                    error_log = f.read()
                    if error_log:
                        print(f"   错误日志: {error_log[-500:]}")  # 显示最后500字符
            except:
                pass
    
    if success_count > 0:
        print(f"\n🎉 成功启动 {success_count}/3 个服务!")
        
        print("\n=== 访问地址 ===")
        print("基础MES服务:  http://175.27.138.86:8004/admin/")
        print("完整MES服务:  http://175.27.138.86:8005/admin/")
        print("Django管理:   http://175.27.138.86:8006/admin/")
        
        print("\n=== 登录信息 ===")
        print("用户名: admin")
        print("密码: admin123")
        
        print("\n=== 系统功能 ===")
        print("✅ 人员管理 (Person)")
        print("✅ 客户管理 (Customer)")
        print("✅ 仓库管理 (Warehouse)")
        print("✅ 物料管理 (Material)")
        print("✅ 设备管理 (Device)")
        print("✅ 产品目录 (Product Catalog)")
        print("✅ 质量管理 (Quality)")
        print("✅ 维护管理 (Maintenance)")
        print("✅ 条码管理 (Barcode)")
        print("✅ 文件管理 (File)")
        print("✅ 通知公告 (Announcements)")
        print("✅ 消息系统 (Messages)")
        print("✅ 活动流 (Activity Stream)")
        
        print("\n=== 查看日志 ===")
        for service in services:
            print(f"tail -f {service['log']}")
            
        print("\n=== 停止服务 ===")
        print("pkill -f 'python manage.py runserver'")
        
        return True
    else:
        print("\n❌ 所有服务启动失败!")
        print("请检查日志文件获取详细错误信息:")
        for service in services:
            print(f"  cat {service['log']}")
        return False

if __name__ == '__main__':
    try:
        success = start_mes_services()
        sys.exit(0 if success else 1)
    except KeyboardInterrupt:
        print("\n用户中断操作")
        sys.exit(1)
    except Exception as e:
        print(f"\n启动失败: {e}")
        sys.exit(1) 